import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Tag,
  Popconfirm 
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import api from '../services/authService';

const { Option } = Select;

interface Environment {
  id: number;
  name: string;
  display_name: string;
  description: string;
  env_type: string;
  base_url: string;
  is_active: boolean;
  created_at: string;
}

const Environments: React.FC = () => {
  const [environments, setEnvironments] = useState<Environment[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingEnv, setEditingEnv] = useState<Environment | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchEnvironments();
  }, []);

  const fetchEnvironments = async () => {
    setLoading(true);
    try {
      const response = await api.get('/environments/');
      setEnvironments(response.data);
    } catch (error) {
      message.error('获取环境列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingEnv(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (env: Environment) => {
    setEditingEnv(env);
    form.setFieldsValue(env);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await api.delete(`/environments/${id}`);
      message.success('删除成功');
      fetchEnvironments();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingEnv) {
        await api.put(`/environments/${editingEnv.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/environments/', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchEnvironments();
    } catch (error) {
      message.error(editingEnv ? '更新失败' : '创建失败');
    }
  };

  const getEnvTypeColor = (type: string) => {
    const colors: { [key: string]: string } = {
      dev: 'blue',
      test: 'orange',
      staging: 'purple',
      prod: 'red'
    };
    return colors[type] || 'default';
  };

  const columns = [
    {
      title: '环境名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '显示名称',
      dataIndex: 'display_name',
      key: 'display_name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '环境类型',
      dataIndex: 'env_type',
      key: 'env_type',
      render: (type: string) => (
        <Tag color={getEnvTypeColor(type)}>
          {type.toUpperCase()}
        </Tag>
      ),
    },
    {
      title: '基础URL',
      dataIndex: 'base_url',
      key: 'base_url',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '活跃' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: Environment) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个环境吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h1>环境管理</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          创建环境
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={environments}
        loading={loading}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title={editingEnv ? '编辑环境' : '创建环境'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="环境名称"
            rules={[{ required: true, message: '请输入环境名称' }]}
          >
            <Input placeholder="请输入环境名称" />
          </Form.Item>

          <Form.Item
            name="display_name"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入显示名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入环境描述" />
          </Form.Item>

          <Form.Item
            name="env_type"
            label="环境类型"
            rules={[{ required: true, message: '请选择环境类型' }]}
          >
            <Select placeholder="请选择环境类型">
              <Option value="dev">开发环境</Option>
              <Option value="test">测试环境</Option>
              <Option value="staging">预发布环境</Option>
              <Option value="prod">生产环境</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="base_url"
            label="基础URL"
          >
            <Input placeholder="请输入基础URL" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Environments;
